<template>
  <el-table-column v-bind="computedColumnOptions" v-if="exTypes.indexOf(computedColumnOptions.type) > -1"></el-table-column>
  <el-table-column ref="column" v-bind="computedColumnOptions" v-else>
    <template slot="header" slot-scope="scope">
      <template v-if="options.header">
        <column-content :scope="scope" :options="options.header" :prop='options.prop'></column-content>
      </template>
      <template v-else>
        {{ options.label }}
      </template>
    </template>
    <template slot-scope="scope">
      <template v-if="options.children && options.children.length > 0">
        <column v-for="(item, index) in options.children" :key="index" :options="item"></column>
      </template>
      <template v-else>
        <template v-if="options.body">
          <column-content :scope="scope" :options="options.body" :prop='options.prop'></column-content>
        </template>
        <template v-else>{{ format(scope.row[options.prop]) }}</template>
      </template>
    </template>
  </el-table-column>
</template>
<script>
import ColumnContent from './ColumnContent'
import { TableColumn } from 'element-ui'
import format from './utils/format'
export default {
  name: 'Column',
  components: { ColumnContent },
  props: {
    options: { // 配置
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      exTypes: ['selection', 'index', 'expand']
    }
  },
  methods: {
    format(val) {
      if (typeof this.options.format === 'function') {
        return this.options.format(val)
      } else if (typeof this.options.format === 'string') { // 字符串格式为 type|arg1|arg2|...|argn
        let arr = this.options.format.split('|')
        let type = arr[0]
        arr.shift()
        let args = arr
        return format[type](val, ...args)
      } else {
        return val
      }
    }
  },
  computed: {
    computedColumnOptions() {
      let keys = Object.keys(TableColumn.props).map(key => key.toLocaleUpperCase())
      let result = {}
      for (let key in this.options) {
        if (keys.indexOf(key.replace(/-/g, '').toLocaleUpperCase()) > -1) {
          result[key] = this.options[key]
        }
      }
      return {...{headerAlign: 'center', showOverflowTooltip: true}, ...result}
    },
    computedHeader() {
      return this.options.header
    },
    computedBody() {
      return this.options.body
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
